<template>
  <div class="enterprise-detail-wrapper">
    <!-- 顶部导航栏 -->
    <HomeNavBar />
    
    <div class="enterprise-detail-container" v-loading="loading">
      <el-button 
        :icon="ArrowLeft" 
        @click="goBack" 
        class="back-button"
        text
      >
        返回企业列表
      </el-button>

      <div v-if="enterpriseInfo" class="enterprise-detail">
        <!-- 企业头部信息 -->
        <el-card class="header-card" shadow="never">
          <div class="enterprise-header-detail">
            <div class="enterprise-logo-large">
              <el-image
                :src="getImageUrl(enterpriseInfo.imageUrl)"
                :alt="enterpriseInfo.enterpriseName"
                fit="cover"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="enterprise-basic-info">
              <div class="title-row">
                <h1 class="enterprise-name-large">{{ enterpriseInfo.enterpriseName }}</h1>
                <el-tag
                  :type="enterpriseInfo.status === 'active' ? 'success' : 'info'"
                  size="large"
                >
                  {{ enterpriseInfo.status === 'active' ? '活跃' : '暂停' }}
                </el-tag>
              </div>
              <p class="enterprise-description-full">{{ enterpriseInfo.description }}</p>
            </div>
          </div>
        </el-card>

        <!-- 企业详细信息 -->
        <el-row :gutter="20">
          <el-col :span="16">
            <!-- 福利待遇 -->
            <el-card v-if="enterpriseInfo.benefits" class="info-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <h3>福利待遇</h3>
                </div>
              </template>
              <div class="benefits-content">
                <el-tag
                  v-for="(benefit, index) in formatBenefits(enterpriseInfo.benefits)"
                  :key="index"
                  type="success"
                  class="benefit-tag"
                >
                  {{ benefit }}
                </el-tag>
              </div>
            </el-card>

            <!-- 在招岗位 -->
            <el-card class="info-card jobs-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <h3>在招岗位 ({{ jobList.length }})</h3>
                </div>
              </template>
            <div v-if="jobList.length > 0" class="jobs-list">
                <div
                  v-for="job in jobList"
                  :key="job.jobId"
                  class="job-item"
                  @click="viewJobDetail(job.jobId)"
                >
                  <div class="job-header">
                    <div class="job-title-row">
                      <h4 class="job-name">{{ job.jobName }}</h4>
                      <el-tag v-if="job.isTop" type="danger" size="small">置顶</el-tag>
                    </div>
                    <div class="job-salary" v-if="job.salary">
                      <span class="salary-text">{{ job.salary }}</span>
                    </div>
                  </div>
                  <div class="job-info-row">
                    <span v-if="job.location" class="job-info-item">
                      <el-icon><Location /></el-icon>
                      {{ job.location }}
                    </span>
                    <span v-if="job.experience" class="job-info-item">
                      <el-icon><Briefcase /></el-icon>
                      {{ job.experience }}
                    </span>
                    <span v-if="job.education" class="job-info-item">
                      <el-icon><School /></el-icon>
                      {{ job.education }}
                    </span>
                    <span v-if="job.hiringCount" class="job-info-item">
                      招聘 {{ job.hiringCount }} 人
                    </span>
                  </div>
                  <div class="job-description" v-if="job.jobDescription">
                    <p>{{ truncateText(job.jobDescription, 120) }}</p>
                  </div>
                  <div class="job-footer">
                    <div class="job-footer-left">
                      <span class="job-time">{{ formatDate(job.createTime) }} 发布</span>
                      <span class="job-views" v-if="job.viewCount">
                        <el-icon><View /></el-icon>
                        {{ job.viewCount }} 次浏览
                      </span>
                    </div>
                    <div class="job-footer-right">
                      <el-button type="primary" size="small" @click.stop="handleApply(job.jobId)">投递</el-button>
                    </div>
                  </div>
                </div>
              </div>
              <el-empty v-else description="暂无在招岗位" :image-size="120" />
            </el-card>

            <!-- 投递对话框 -->
            <ApplyDialog
              v-model="applyDialogVisible"
              :job-id="currentJobId"
            />
          </el-col>
          
          <el-col :span="8">
            <!-- 企业统计 -->
            <el-card class="info-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <h3>企业信息</h3>
                </div>
              </template>
              <div class="info-items">
                <div class="info-item">
                  <span class="label">注册时间：</span>
                  <span class="value">{{ formatDate(enterpriseInfo.createTime) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">更新时间：</span>
                  <span class="value">{{ formatDate(enterpriseInfo.updateTime) }}</span>
                </div>
                <div class="info-item" v-if="enterpriseInfo.jobCount !== undefined">
                  <span class="label">在招岗位：</span>
                  <span class="value highlight">{{ enterpriseInfo.jobCount }} 个</span>
                </div>
                <div class="info-item" v-if="enterpriseInfo.reviewCount !== undefined">
                  <span class="label">企业评价：</span>
                  <span class="value">{{ enterpriseInfo.reviewCount }} 条</span>
                </div>
              </div>
            </el-card>

            <!-- 企业评价 -->
            <el-card class="info-card reviews-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <h3>用户评价 ({{ reviews.length }})</h3>
                  <el-button type="primary" size="small" @click="handleAddReview">
                    <el-icon><Plus /></el-icon>
                    写评价
                  </el-button>
                </div>
              </template>
              
              <div class="reviews-content">
                <div v-if="reviewsLoading" class="loading-container">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  <span>加载中...</span>
                </div>
                
                <div v-else-if="reviews.length === 0" class="no-reviews">
                  <el-empty description="暂无评价">
                    <el-button type="primary" @click="handleAddReview">写第一个评价</el-button>
                  </el-empty>
                </div>
                
                <div v-else class="reviews-list">
                  <div v-for="review in reviews" :key="review.reviewId" class="review-item">
                    <div class="review-header">
                      <div class="reviewer-info">
                        <el-avatar :size="32">{{ (review.userName || '匿名').charAt(0) }}</el-avatar>
                        <div class="reviewer-details">
                          <span class="reviewer-name">{{ review.userName || '匿名用户' }}</span>
                          <el-rate
                            :model-value="Number(review.rating)"
                            disabled
                            size="small"
                          />
                        </div>
                      </div>
                      <span class="review-time">{{ formatDate(review.reviewTime) }}</span>
                    </div>
                    <div class="review-content">
                      <p>{{ review.content }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <el-empty v-else-if="!loading" description="企业信息不存在" />
    </div>

    <!-- 评价对话框 -->
    <ReviewDialog
      v-model:visible="reviewDialogVisible"
      :enterprise-id="route.params.id"
      @success="handleReviewSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Picture, Location, Briefcase, School, View, Plus, Loading, ChatDotRound } from '@element-plus/icons-vue'
import HomeNavBar from '@/components/HomeNavBar.vue'
import ReviewDialog from '@/components/job/ReviewDialog.vue'
import ApplyDialog from '@/components/job/ApplyDialog.vue'
import instance from '@/utils/request'
import { getEnterpriseReviews } from '@/api/enterprise'

const router = useRouter()
const route = useRoute()

// 数据
const loading = ref(false)
const enterpriseInfo = ref(null)
const jobList = ref([])
const reviews = ref([])
const reviewsLoading = ref(false)
const reviewDialogVisible = ref(false)
const applyDialogVisible = ref(false)
const currentJobId = ref(null)

// 获取企业详情
const fetchEnterpriseDetail = async () => {
  const enterpriseId = route.params.id
  if (!enterpriseId) {
    ElMessage.error('企业ID不存在')
    return
  }

  loading.value = true
  try {
    const response = await instance.request({
      method: 'GET',
      url: `/enterprises/${enterpriseId}`
    })

    if (response.code === 0) {
      enterpriseInfo.value = response.data
      // 从企业信息中提取岗位列表（如果有）
      if (response.data.jobs && Array.isArray(response.data.jobs)) {
        jobList.value = response.data.jobs
      } else {
        // 如果没有，单独获取岗位列表
        await fetchJobList(enterpriseId)
      }
      // 获取企业评价
      await fetchReviews(enterpriseId)
    } else {
      ElMessage.error(response.msg || '获取企业信息失败')
    }
  } catch (error) {
    console.error('获取企业详情失败:', error)
    ElMessage.error('获取企业信息失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取企业岗位列表
const fetchJobList = async (enterpriseId) => {
  try {
    const response = await instance.request({
      method: 'GET',
      url: '/jobs',
      params: {
        enterpriseId,
        status: 'active',
        page: 1,
        pageSize: 50
      }
    })

    if (response.code === 0) {
      jobList.value = response.data.list || []
    }
  } catch (error) {
    console.error('获取岗位列表失败:', error)
  }
}

// 查看岗位详情
const viewJobDetail = (jobId) => {
  // 这里可以跳转到岗位详情页，如果还没有创建，可以先跳转到岗位列表页
  router.push(`/jobs/${jobId}`)
}

const handleApply = (jobId) => {
  currentJobId.value = jobId
  applyDialogVisible.value = true
}

// 获取企业评价列表
const fetchReviews = async (enterpriseId) => {
  if (!enterpriseId) return
  
  reviewsLoading.value = true
  try {
    const response = await getEnterpriseReviews(enterpriseId, {
      page: 1,
      pageSize: 100
    })
    
    let apiReviews = []
    
    // 处理不同格式的响应
    if (response && response.data) {
      if (Array.isArray(response.data)) {
        apiReviews = response.data
      } else if (response.data.list && Array.isArray(response.data.list)) {
        apiReviews = response.data.list
      } else if (response.data.data && Array.isArray(response.data.data)) {
        apiReviews = response.data.data
      }
    }
    
    // 格式化评价数据
    reviews.value = apiReviews
      .map(review => ({
        reviewId: review.reviewId || review.review_id,
        enterpriseId: Number(review.enterpriseId || review.enterprise_id || enterpriseId),
        userId: review.userId || review.user_id,
        userName: review.userName || review.user_name || '匿名用户',
        content: review.content || '',
        rating: Number(review.rating) || 0,
        reviewTime: review.reviewTime || review.review_time || new Date().toISOString()
      }))
      .sort((a, b) => {
        const timeA = new Date(a.reviewTime || 0).getTime()
        const timeB = new Date(b.reviewTime || 0).getTime()
        return timeB - timeA
      })
  } catch (error) {
    console.error('获取评价列表失败:', error)
    reviews.value = []
  } finally {
    reviewsLoading.value = false
  }
}

// 处理添加评价
const handleAddReview = () => {
  reviewDialogVisible.value = true
}

// 处理评价提交成功
const handleReviewSuccess = async (newReview) => {
  ElMessage.success('评价提交成功！')
  reviewDialogVisible.value = false
  // 重新获取评价列表
  await fetchReviews(route.params.id)
}

// 返回
const goBack = () => {
  router.push('/enterprises')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `http://localhost:7001${url}`
}

// 格式化福利待遇
const formatBenefits = (benefits) => {
  if (!benefits) return []
  // 如果是字符串，按换行分割
  if (typeof benefits === 'string') {
    return benefits.split('\n').filter(item => item.trim())
  }
  // 如果是数组，直接返回
  if (Array.isArray(benefits)) {
    return benefits
  }
  return []
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 初始化
onMounted(() => {
  fetchEnterpriseDetail()
})
</script>

<style lang="scss" scoped>
.enterprise-detail-wrapper {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.enterprise-detail-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px 20px;
}

.back-button {
  margin-bottom: 20px;
  color: #409eff;
}

.enterprise-detail {
  .header-card {
    margin-bottom: 20px;
    border-radius: 12px;
    
    :deep(.el-card__body) {
      padding: 30px;
    }
  }

  .enterprise-header-detail {
    display: flex;
    gap: 24px;
    
    .enterprise-logo-large {
      width: 120px;
      height: 120px;
      border-radius: 12px;
      overflow: hidden;
      flex-shrink: 0;
      background: #f0f0f0;
      
      .el-image {
        width: 100%;
        height: 100%;
      }
      
      .image-slot {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f0f0f0;
        
        .el-icon {
          font-size: 48px;
          color: #c0c4cc;
        }
      }
    }
    
    .enterprise-basic-info {
      flex: 1;
      
      .title-row {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 12px;
        
        .enterprise-name-large {
          font-size: 28px;
          font-weight: 600;
          color: #303133;
          margin: 0;
        }
      }
      
      .enterprise-description-full {
        font-size: 16px;
        color: #606266;
        line-height: 1.8;
        margin: 0;
      }
    }
  }

  .info-card {
    margin-bottom: 20px;
    border-radius: 12px;
    
    .card-header {
      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .benefits-content {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      
      .benefit-tag {
        padding: 8px 16px;
        font-size: 14px;
      }
    }
    
    .info-items {
      .info-item {
        display: flex;
        padding: 12px 0;
        border-bottom: 1px solid #ebeef5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .label {
          color: #909399;
          font-size: 14px;
          min-width: 100px;
        }
        
        .value {
          color: #303133;
          font-size: 14px;
          font-weight: 500;

          &.highlight {
            color: #409eff;
            font-weight: 600;
          }
        }
      }
    }
  }

  .jobs-card {
    margin-top: 20px;

    .jobs-list {
      .job-item {
        padding: 20px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        margin-bottom: 16px;
        cursor: pointer;
        transition: all 0.3s;
        background: #fff;

        &:hover {
          border-color: #409eff;
          box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
          transform: translateY(-2px);
        }

        &:last-child {
          margin-bottom: 0;
        }

        .job-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 12px;

          .job-title-row {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;

            .job-name {
              font-size: 18px;
              font-weight: 600;
              color: #303133;
              margin: 0;
            }
          }

          .job-salary {
            .salary-text {
              font-size: 18px;
              font-weight: 600;
              color: #f56c6c;
            }
          }
        }

        .job-info-row {
          display: flex;
          flex-wrap: wrap;
          gap: 20px;
          margin-bottom: 12px;
          color: #909399;
          font-size: 14px;

          .job-info-item {
            display: flex;
            align-items: center;
            gap: 4px;

            .el-icon {
              font-size: 16px;
            }
          }
        }

        .job-description {
          margin-bottom: 12px;

          p {
            margin: 0;
            color: #606266;
            font-size: 14px;
            line-height: 1.6;
          }
        }

        .job-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-top: 12px;
          border-top: 1px solid #f0f0f0;
          font-size: 13px;
          color: #909399;

          .job-views {
            display: flex;
            align-items: center;
            gap: 4px;

            .el-icon {
              font-size: 14px;
            }
          }
        }
      }
    }
  }

  .reviews-card {
    margin-top: 20px;

    .reviews-content {
      .loading-container {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 40px 0;
        color: #666;
      }

      .no-reviews {
        text-align: center;
        padding: 40px 20px;
      }

      .reviews-list {
        display: flex;
        flex-direction: column;
        gap: 16px;

        .review-item {
          border: 1px solid #ebeef5;
          border-radius: 8px;
          padding: 16px;
          background: #fff;
          transition: all 0.3s;

          &:hover {
            border-color: #409eff;
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
          }

          .review-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .reviewer-info {
              display: flex;
              align-items: center;
              gap: 10px;

              .reviewer-details {
                display: flex;
                flex-direction: column;
                gap: 4px;

                .reviewer-name {
                  font-weight: 500;
                  color: #303133;
                  font-size: 14px;
                }
              }
            }

            .review-time {
              color: #909399;
              font-size: 12px;
            }
          }

          .review-content {
            p {
              margin: 0;
              color: #606266;
              line-height: 1.6;
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}

// 响应式
@media (max-width: 768px) {
  .enterprise-header-detail {
    flex-direction: column;
    text-align: center;
  }
}
</style>

